package com.iot.controller;

import com.iot.core.LResult;
import com.iot.pojo.MTmenu;
import com.iot.pojo.MTusers;
import com.iot.service.TmenuService;
import com.iot.service.TusersService;
import com.iot.util.JWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/")
public class BackgroundController extends BaseController {
    @Autowired
    private TusersService service;
    @Autowired
    private TmenuService tmenuService;

    @RequestMapping(value = "login", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String login(HttpServletRequest request) {
        request.removeAttribute("error");
        return "/login";
    }

    @ResponseBody
    @RequestMapping(value = "login", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String login(String username, String password, HttpServletRequest request, HttpSession httpSession) {
        try {
            //String token = Token.genetateToken();
            String inputVerifyCode=request.getParameter("verifyCode");
            String verifyCodeValue=(String) request.getSession().getAttribute("verifyCodeValue");
            System.out.println("Session中的验证码值------>"
                    + verifyCodeValue);
//            if(!verifyCodeValue.equals(inputVerifyCode.toUpperCase())){
//                return LResult.Error("验证码错误！").toJson();
//            }
            MTusers mTusers = service.login(username, password);
            if (mTusers != null) {
                String token = JWT.sign(mTusers, 60L * 1000L * 30L);

                //httpSession.setAttribute(SESSION_TOKEN, token);
                //httpSession.setAttribute(USER_ID, mTusers.getUSERS_ID());
                Map<String, Object> map = new HashMap<>();
                map.put("USERS_ID", mTusers.getUSERS_ID());
                map.put("SNAME", mTusers.getSNAME());
                map.put("ROLE_ID", mTusers.getROLE_ID());
                map.put("DEPT_ID", mTusers.getDEPT_ID());
                map.put("EMP_ID", mTusers.getEMP_ID());
                map.put("PROVINCE_ID", mTusers.getPROVINCE_ID());
                map.put("CITY_ID", mTusers.getCITY_ID());
                map.put("APP_ID", mTusers.getAPP_ID());
                map.put("BADMIN", mTusers.getBADMIN());
                // map.put("AREA_ID",mTusers.getAREA_ID());

                map.put("TOKEN", token);
                return LResult.Success(map).toJson();
            } else {
                return LResult.Error("用户不存在").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return LResult.Error(e.getMessage()).toJson();
        }
        //return  LResult.Error("redirect:index.shtml");
    }

    @RequestMapping("index")
    public String index(Model model, HttpServletRequest request)
            throws Exception {
        return "/index";
    }

    @ResponseBody
    @RequestMapping("auth")
    public String getMenuByUserId(Integer userId, HttpServletRequest request) {
        try {
            List<MTmenu> list = service.getMenuByUserId(userId);
            return LResult.Success(list).toJson();
        } catch (Exception e) {
            e.printStackTrace();
            return LResult.Error(e.getMessage()).toJson();
        }

    }

    /**
     * 获取验证码
     *
     * @param response
     * @param session
     */
    @RequestMapping("/getVerifyCode")
    public void generate(HttpServletResponse response, HttpSession session) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        String verifyCodeValue = drawImg(output);

        session.setAttribute("verifyCodeValue", verifyCodeValue);

        try {
            ServletOutputStream out = response.getOutputStream();
            output.writeTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 绘画验证码
     *
     * @param output
     * @return
     */
    private String drawImg(ByteArrayOutputStream output) {
        String code = "";
        // 随机产生4个字符
        for (int i = 0; i < 4; i++) {
            code += randomChar();
        }
        int width = 70;
        int height = 25;
        BufferedImage bi = new BufferedImage(width, height,
                BufferedImage.TYPE_3BYTE_BGR);
        Font font = new Font("Times New Roman", Font.PLAIN, 20);
        // 调用Graphics2D绘画验证码
        Graphics2D g = bi.createGraphics();
        g.setFont(font);
        Color color = new Color(66, 2, 82);
        g.setColor(color);
        g.setBackground(new Color(226, 226, 240));
        g.clearRect(0, 0, width, height);
        FontRenderContext context = g.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(code, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = bounds.getY();
        double baseY = y - ascent;
        g.drawString(code, (int) x, (int) baseY);
        g.dispose();
        try {
            ImageIO.write(bi, "jpg", output);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 随机参数一个字符
     *
     * @return
     */
    private char randomChar() {
        Random r = new Random();
        String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
        return s.charAt(r.nextInt(s.length()));
    }

}
